package com.example.mybatisdemo.mapper;

import com.example.mybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper  //mybatis告知Spring，把对象交给Spring管理
public interface UserInfoMapper { //接口

    //结果映射方法1:对mysql查询字段重命名
    @Select("select id,username,password,age,gender,phone,delete_flag as deleteFlag," +
            "create_time as createTime,update_time as updateTime from userinfo") //方法实现
    List<UserInfo> selectAll(); //方法声明

    /**
     *结果映射
     *方法2:使用注解
     */
    @Results(id = "BaseMap",value = {
            @Result(column = "delete_flag",property = "deleteFlag"),// 列名+属性名
            @Result(column = "create_flag",property = "create_flag"),
            @Result(column = "update_flag",property = "update_flag"),
    })
    @Select("select * from userinfo")
    List<UserInfo> selectAll2();

    @ResultMap(value = "BaseMap") // 复用Result的定义
    @Select("select * from userinfo where id = #{id}")
    List<UserInfo> selectOne(Integer id);

    @ResultMap(value = "BaseMap")
    @Select("select * from userinfo where id = #{userId}")//只有一个参数时,此处命名可随意,但最好与下方一致
    List<UserInfo> selectOne2(@Param("userId") Integer id);

    /**
     * 结果映射
     * 方法3: 使用配置的方式, 自动转驼峰
     * (最优雅的方式了)
     */
    @Select("select * from userinfo")
    List<UserInfo> selectAll3();

    @ResultMap(value = "BaseMap")
    @Select("select * from userinfo where username= #{username}")
    List<UserInfo> selectByName(String username);


    //返回自增id
    @Options(useGeneratedKeys = true,keyProperty = "id") //使用数据库自动增长的主键,并从table中id字段里面把数据放到传入对象的成员变量id里面
    //即获取插入时的id
    @Insert("insert into userinfo (username,password,age,gender,phone)" +
            " values (#{username},#{password},#{age},#{gender},#{phone})")
    Integer insert(UserInfo userInfo);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into userinfo (username,password,age,gender,phone)" +
            " values (#{userInfo.username},#{userInfo.password},#{userInfo.age},#{userInfo.gender},#{userInfo.phone})")
    Integer insert2(@Param("userInfo") UserInfo userInfo);
    // 虽然重命名的名称相等,但userInfo.字段名的方式去获取values是可行的

    @Delete("delete from userinfo where id = #{id}")
    void delete(Integer id);// 返回类型是void时不返回任何东西,查一下表就会发现变化

    @Update("update userinfo set age = #{age} where id = #{id}")
    Integer update(UserInfo userInfo);
}
